/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.common.custom.editor;

import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyEditorSupport;

/**
 * 字符串编辑器，该编辑器主要用于处理 password 属性
 *
 * @author 挺好的 2023年05月30日 8:27
 */
public class StringEditor extends PropertyEditorSupport {

    private boolean emptyAsNull;

    public StringEditor (boolean emptyAsNull) {
        this.emptyAsNull = emptyAsNull;
    }

    /**
     * @return value ==null 返回空字符串
     */
    @Override
    public String getAsText () {
        Object value = this.getValue();
        return value != null ? value.toString() : StringUtils.EMPTY;
    }

    /**
     * emptyAsNull && StringUtils.isEmpty，set value null
     *
     * @param text
     *         字符串
     */
    @Override
    public void setAsText (String text) {
        if (this.emptyAsNull && StringUtils.isEmpty(text)) {
            this.setValue(null);
        } else {
            this.setValue(text);
        }
    }
}
